package dao

import (
	"time"
)

type Device struct {
	Did int `gorm:"column:d_id" json:"d_id"`
	Uid int `gorm:"column:uid" json:"uid"`
	Name string `gorm:"column:name" json:"name"`
	Dtype int `gorm:"column:dtype" json:"dtype"`
	Brand int `gorm:"column:brand" json:"brand"`
	Model int `gorm:"column:model" json:"model"`
	DataType int `gorm:"column:data_type" json:"data_type"`
	ManageType int `gorm:"column:manage_type" json:"manage_type"`
	Ctime int64 `gorm:"column:c_time" json:"c_time"`
	Dtime int64 `gorm:"column:d_time" json:"d_time"`
}

func (t *Device)Create(device Device) error {

	device.Ctime = time.Now().Unix()
	err := db.Create(device).Error
	return err

}
/**

 */
func (t *Device)Delete(where map[string]interface{}) error {

	upd := Device{
		Dtime:time.Now().Unix(),
	}
	err := db.Model(&t).Where(where).Update(upd).Error
	if err != nil{
		return err
	}
	return nil

}
func (t *Device)Update(d Device,w map[string]interface{}) error {

	err := db.Model(&t).Where(w).Updates(&d).Error
	if err != nil{
		return err
	}
	return nil

}

func (t *Device)First(d_id int) (error ,*Device){

	err :=db.Where("d_id = ?",d_id).First(&t).Error

	if err != nil{
		return err,nil
	}
	if t.Did > 0{
		return err,t
	}
	return nil,t

}

func (t *Device) Find(pageSize int, pageIndex int) ([]Device, int, error) {
	var doc []Device

	table := db.Select("*")
	if t.Dtype != 0 {
		table = table.Where("dtype = ?", t.Dtype)
	}
	if t.Name != "" {
		table = table.Where("name like ?", "%" + t.Name + "%")
	}
	if t.Brand != 0 {
		table = table.Where("brand = ?", t.Brand)
	}
	if t.Model != 0 {
		table = table.Where("model like ?", t.Model)
	}

	var count int

	if err := table.Table("bc_device").
		Offset((pageIndex - 1) * pageSize).
		Order("d_id desc").
		Limit(pageSize).
		Find(&doc).
		Error; err != nil {
		return nil, 0, err
	}
	table.Table("bc_device").Count(&count)
	return doc, count, nil
}
